package com.qiyue.controller;


import com.qiyue.pojo.Myfile;
import com.qiyue.service.MyFileServer;
import com.qiyue.service.impl.MyFileServerImpl;
import com.qiyue.utils.Result;
import com.qiyue.utils.StatusCode;
import com.qiyue.utils.FileUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author 杜宇宙
 * @dateTime 2022/2/16
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
public class MyFileController {
    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private MyFileServer myFileServer;

    private static Logger logger = Logger.getLogger(MyFileServerImpl.class);

    /**
     * 上传文件
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()){
            logger.warn("文件为空警告"+"------------------"+new Date());
            return new Result(false, StatusCode.ERROR,"文件为空");
        }
        //将文件保存
        Myfile myfile = fileUtil.uploadFile(file);
        //将元数据上传数据库
        if (myFileServer.upload(myfile)) {
            return new Result(true,StatusCode.OK,"文件上传成功！",myfile.getUuid());
        }
        logger.error("文件上传错误信息："+request.getRemoteAddr()+"的用户，文件上传失败！请检查数据库");
        return new Result(false, StatusCode.SQLERROR,"文件上传失败");
    }

    /**
     * 下载文件
     */
    @GetMapping("/download")
    public Result download(@RequestParam("uuid") String uuid, HttpServletResponse response) throws FileNotFoundException {
        //通过uuid查询文件类型,拼接文件名称
        String fileName = myFileServer.findFileType(uuid);
        //文件下载
        Boolean download = fileUtil.download(response, fileName);
        if (download){
            return new Result(true,StatusCode.OK,"下载成功");
        }else {
            return new Result(false, StatusCode.FILEERROR,"下载失败");
        }

    }

    @GetMapping("/fileDate")
    public Result fileDate(@RequestParam("uuid") String uuid){
        Map<String,Object> myfileMap = myFileServer.findByUUID(uuid);
        if (myfileMap!=null){
            return new Result(true,StatusCode.OK,"查询成功！",myfileMap);
        }else {
            return new Result(false,StatusCode.ERROR,"查询失败！");
        }
    }




}
